import { authApi } from './api';

/**
 * 认证服务 - 处理登录、注册等认证相关功能
 */
export const authService = {
  /**
   * 用户登录
   * @param {string} phone - 手机号
   * @param {string} password - 密码
   * @param {boolean} rememberMe - 记住我
   * @returns {Promise} - 返回登录结果
   */
  async login(phone, password, rememberMe = false) {
    try {
      const response = await authApi.login({
        username: phone, // 使用手机号作为用户名
        password,
        rememberMe
      });

      // 处理Spring Boot返回的数据结构
      if (response && response.data) {
        const { data } = response;
        if (data.token) {
          localStorage.setItem('token', data.token);
          if (data.user) {
            localStorage.setItem('user', JSON.stringify(data.user));
          }
          return { success: true, data: data };
        }
      }

      return { success: false, message: '登录失败，请检查响应数据' };
    } catch (error) {
      console.error('登录失败:', error);
      return {
        success: false,
        message: error.response?.data?.message || '登录失败，请检查网络连接'
      };
    }
  },

  /**
   * 用户注册
   * @param {string} phone - 手机号
   * @param {string} password - 密码
   * @param {string} confirmPassword - 确认密码
   * @param {string} verificationCode - 验证码
   * @returns {Promise} - 返回注册结果
   */
  async register(phone, password, confirmPassword, verificationCode) {
    try {
      const response = await authApi.register({
        phone,
        password,
        confirmPassword,
        verificationCode
      });
      
      return { success: true, data: response };
    } catch (error) {
      console.error('注册失败:', error);
      return { 
        success: false, 
        message: error.response?.data?.message || '注册失败，请检查网络连接' 
      };
    }
  },

  /**
   * 发送注册验证码
   * @param {string} phone - 手机号
   * @returns {Promise} - 返回发送结果
   */
  async sendSmsCode(phone, type = 'register') {
    try {
      const response = await authApi.sendSmsCode(phone, type);
      return { success: true, data: response.data };
    } catch (error) {
      console.error('发送验证码失败:', error);
      return {
        success: false,
        message: error.response?.data?.message || '发送验证码失败，请稍后再试'
      };
    }
  },

  async loginWithSmsCode(phone, code) {
    try {
      const response = await authApi.loginWithCode({
        phone,
        code
      });

      // 处理Spring Boot返回的数据结构
      if (response && response.data) {
        const { data } = response;
        if (data.token) {
          localStorage.setItem('token', data.token);
          if (data.user) {
            localStorage.setItem('user', JSON.stringify(data.user));
          }
          return { success: true, data: data };
        }
      }

      return { success: false, message: '验证码登录失败' };
    } catch (error) {
      console.error('验证码登录失败:', error);
      return {
        success: false,
        message: error.response?.data?.message || '验证码登录失败，请检查网络连接'
      };
    }
  },

  /**
   * 检查用户是否已登录
   * @returns {boolean} - 是否已登录
   */
  isLoggedIn() {
    return !!localStorage.getItem('token');
  },

  /**
   * 从API获取当前用户信息
   * @returns {Promise} - 包含用户信息的Promise
   */
  async fetchCurrentUser() {
    try {
      const response = await authApi.getProfile();
      if (response && response.data) {
        localStorage.setItem('user', JSON.stringify(response.data));
        return { success: true, data: response.data };
      }
      return { success: false, message: '获取用户信息失败' };
    } catch (error) {
      console.error('获取用户信息失败:', error);
      return { 
        success: false, 
        message: error.response?.data?.message || '获取用户信息失败，请检查网络连接' 
      };
    }
  },

  /**
   * 获取当前登录用户信息
   * @param {boolean} [fetchFromApi=false] - 是否从API获取最新信息
   * @returns {Object|null} - 用户信息或null
   */
  getCurrentUser(fetchFromApi = false) {
    if (fetchFromApi) {
      this.fetchCurrentUser();
    }
    const userStr = localStorage.getItem('user');
    if (userStr) {
      try {
        return JSON.parse(userStr);
      } catch (e) {
        console.error('解析用户信息失败', e);
        return null;
      }
    }
    return null;
  },

  async getCaptchaImage() {
    try {
      const response = await captchaApi.getCaptchaImage();
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取验证码图片失败:', error);
      return { 
        success: false, 
        message: error.response?.data?.message || '获取验证码失败，请重试' 
      };
    }
  },

  async verifyCaptcha(captchaId, captchaCode) {
    try {
      const response = await captchaApi.verifyCaptcha({ captchaId, captchaCode });
      return { success: true, data: response.data };
    } catch (error) {
      console.error('验证码验证失败:', error);
      return { 
        success: false, 
        message: error.response?.data?.message || '验证码错误，请重新输入' 
      };
    }
  },

  async getVerificationCode(phone) {
    try {
      const response = await authApi.post('/verification-code', { phone });
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取验证码失败:', error);
      return { 
        success: false, 
        message: error.response?.data?.message || '获取验证码失败，请检查网络连接' 
      };
    }
  },

  /**
   * 退出登录
   */
  logout() {
    // 调用后端登出API
    authApi.logout().catch(error => {
      console.error('登出API调用失败:', error);
    });
    
    // 无论API调用成功与否，都清除本地存储
    localStorage.removeItem('token');
    localStorage.removeItem('user');
  }
};

export default authService;